<template>
  <div class="page-box" style="position: relative;">
    <el-form
      ref="formCustomerAccountRef"
      :size="layoutStore.defaultFormItemSize"
      label-width="120px"
      label-position="right"
      @submit.prevent
    >
      <filter-box :item-width="350" @search="refreshFormCustomerAccount()" @reset="resetFormCustomerAccount">
        <el-form-item label="账户类型">
          <el-select
            class="filter-item"
            v-model="formFilter.accountTypeFilter"
            placeholder=""
            :clearable="true"
            :filterable="true"
            @visible-change="accountTypeFilterWidget.onVisibleChange"
          >
            <el-option
              v-for="item in accountTypeFilterWidgetDropdownList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="账户号">
          <el-input
            class="filter-item"
            v-model="formFilter.accountNoFilter"
            type="text"
            placeholder=""
            :clearable="true"
            :show-word-limit="false"
            maxlength=""
          />
        </el-form-item>
        <el-form-item label="所属银行">
          <el-input
            class="filter-item"
            v-model="formFilter.belongBankFilter"
            type="text"
            placeholder=""
            :clearable="true"
            :show-word-limit="false"
            maxlength=""
          />
        </el-form-item>
        <el-form-item label="开户行">
          <el-input
            class="filter-item"
            v-model="formFilter.openAccountBackFilter"
            type="text"
            placeholder=""
            :clearable="true"
            :show-word-limit="false"
            maxlength=""
          />
        </el-form-item>
        <el-form-item label="开户姓名">
          <el-input
            class="filter-item"
            v-model="formFilter.openAccountNameFilter"
            type="text"
            placeholder=""
            :clearable="true"
            :show-word-limit="false"
            maxlength=""
          />
        </el-form-item>
        <el-form-item label="开户手机号">
          <el-input
            class="filter-item"
            v-model="formFilter.openAccountPhoneFilter"
            type="text"
            placeholder=""
            :clearable="true"
            :show-word-limit="false"
            maxlength=""
          />
        </el-form-item>
      </filter-box>
    </el-form>
    <table-box
      ref="formCustomerAccountTable"
      class="page-table"
      :data="formCustomerAccountTableWidgetDataList"
      :size="layoutStore.defaultFormItemSize"
      :row-config="{isCurrent: false, isHover: true}"
      :seq-config="{startIndex: ((formCustomerAccountTableWidgetCurrentPage - 1) * formCustomerAccountTableWidgetPageSize)}"
      :sort-config="{remote: true}"
      :hasExtend="true"
      @sort-change="formCustomerAccountTableWidget.onSortChange"
      @refresh="formCustomerAccountTableWidget.refreshTable()"
    >
      <template #operator>
        <el-button
          type="primary"
          :size="layoutStore.defaultFormItemSize"
          @click="onAddCustomerAccountClick()"
          >
          新建
        </el-button>
        <el-button
          type="primary"
          :size="layoutStore.defaultFormItemSize"
          @click="onExportCustomerAccountClick()"
          >
          导出
        </el-button>
        <el-upload
          class="btn-import"
          :auto-upload="false"
          action=""
          :show-file-list="false"
          accept=".xls,.xlsx"
          style="display: inline-block;"
          :on-change="onImportCustomerAccountClick"
        >
          <template #trigger>
            <el-button
              type="primary"
              :size="layoutStore.defaultFormItemSize"
            >
              导入
            </el-button>
          </template>
        </el-upload>
      </template>
      <vxe-column title="序号" type="seq" :index="formCustomerAccountTableWidget.getTableIndex" :width="80" />
      <vxe-column title="编号" field="accountId" />
      <vxe-column title="客户编号" field="customerId" />
      <vxe-column title="账户类型" field="accountTypeDictMap.name" />
      <vxe-column title="账户号" field="accountNo" />
      <vxe-column title="所属银行" field="belongBank" />
      <vxe-column title="开户行" field="openAccountBack" />
      <vxe-column title="开户姓名" field="openAccountName" />
      <vxe-column title="开户手机号" field="openAccountPhone" />
      <vxe-column title="操作" fixed="right">
        <template v-slot="scope">
          <el-button
            link
            type="primary"
            :size="layoutStore.defaultFormItemSize"
            @click.stop="onEditCustomerAccountClick(scope.row)"
          >
            编辑
          </el-button>
          <el-button
            link
            type="primary"
            :size="layoutStore.defaultFormItemSize"
            @click.stop="onDeleteCustomerAccountClick(scope.row)"
          >
            删除
          </el-button>
        </template>
      </vxe-column>
      <template slot="empty">
        <div class="table-empty unified-font">
          <img src="@/assets/img/empty.png">
          <span>暂无数据</span>
        </div>
      </template>
      <!-- 分页 -->
      <template #pagination>
        <el-row type="flex" justify="end" style="margin-top: 10px;">
          <el-pagination
            :total="formCustomerAccountTableWidgetTotalCount"
            :current-page="formCustomerAccountTableWidgetCurrentPage"
            :page-size="formCustomerAccountTableWidgetPageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, prev, pager, next, sizes"
            @current-change="formCustomerAccountTableWidget.onCurrentPageChange"
            @size-change="formCustomerAccountTableWidget.onPageSizeChange">
          </el-pagination>
        </el-row>
      </template>
    </table-box>
    <label v-if="subPage" class="page-close-box" @click="onCancel()">
      <img src="@/assets/img/back2.png" alt="">
    </label>
  </div>
</template>

<script lang="ts">
export default {
  name: 'formCustomerAccount',
};
</script>

<script setup lang="ts">
import { VxeColumn, VxeTable } from 'vxe-table';
import { ANY_OBJECT } from '@/types/generic';
import { DictData, DictionaryBase } from '@/common/staticDict/types';
import { ElMessage, ElMessageBox, UploadFile } from 'element-plus';
import { useRoute, useRouter } from 'vue-router';
import { useCommon } from '@/common/hooks/useCommon';
import { useLayoutStore, useStaticDictStore } from '@/store';
import { useDownload } from '@/common/hooks/useDownload';
import { useDropdown } from '@/common/hooks/useDropdown';
import { DropdownOptions, ListData } from '@/common/types/list';
import { useTable } from '@/common/hooks/useTable';
import { TableOptions } from '@/common/types/pagination';
import { useUpload } from '@/common/hooks/useUpload';
import { useUploadWidget } from '@/common/hooks/useUploadWidget';
import { DictionaryController } from '@/api/system';
import { treeDataTranslate, findItemFromList, findTreeNodePath, findTreeNode, stringCase } from '@/common/utils';
import { CustomerAccountData } from '@/api/generated/customerAccountController';
import { CustomerAccountController } from '@/api/generated';
import FormEditCustomerAccount from '@/pages/Cust/formEditCustomerAccount.vue';

const router = useRouter();
const route = useRoute();
const layoutStore = useLayoutStore();
const { downloadFile } = useDownload();
const { getUploadHeaders, getUploadActionUrl, fileListToJson, parseUploadData, getPictureList } = useUpload();
const { 
  Delete,
  Search,
  Edit,
  Plus,
  Refresh,
  Picture,
  Dialog,
  mainContextHeight,
  clientHeight,
  checkPermCodeExist,
  parseParams,
  parseArrayParams,
  formatDateByStatsType,
  getDateRangeFilter,
} = useCommon();
// 静态字典
const { staticDict: StaticDict } = useStaticDictStore();

const props = withDefaults(
  defineProps<{
    subPage?: number | string | boolean;
    customerId?: ANY_OBJECT;
  }>(),
  {
    subPage: 0,
    customerId: undefined,
  },
);

const formFilter = reactive({
  // 账户类型
  accountTypeFilter: undefined,
  // 账户号
  accountNoFilter: undefined,
  // 所属银行
  belongBankFilter: undefined,
  // 开户行
  openAccountBackFilter: undefined,
  // 开户姓名
  openAccountNameFilter: undefined,
  // 开户手机号
  openAccountPhoneFilter: undefined,
});
const formFilterCopy = reactive({
  // 账户类型
  accountTypeFilter: undefined,
  // 账户号
  accountNoFilter: undefined,
  // 所属银行
  belongBankFilter: undefined,
  // 开户行
  openAccountBackFilter: undefined,
  // 开户姓名
  openAccountNameFilter: undefined,
  // 开户手机号
  openAccountPhoneFilter: undefined,
});

const onCancel = () => {
  router.go(-1);
  layoutStore.removeCachePage(route.fullPath as string);
  route.meta.refreshParentCachedPage = true;
};

const onResume = () => {
  refreshFormCustomerAccount();
};

/**
 * 表格组件数据获取函数，返回Promise
 */
const loadFormCustomerAccountTableWidgetData = (params: ANY_OBJECT) => {
  if (params == null) params = {};
  params = {
    ...params,
    customerAccountDtoFilter: {
      accountNo: formFilter.accountNoFilter,
      belongBank: formFilter.belongBankFilter,
      openAccountBack: formFilter.openAccountBackFilter,
      openAccountName: formFilter.openAccountNameFilter,
      openAccountPhone: formFilter.openAccountPhoneFilter,
    }
  };
  return new Promise((resolve, reject) => {
    CustomerAccountController.list(params).then(res => {
      resolve({
        dataList: res.data.dataList,
        totalCount: res.data.totalCount
      });
    }).catch(e => {
      reject(e);
    });
  });
};
/**
 * 表格组件数据获取检测函数，返回true正常获取数据，返回false停止获取数据
 */
const loadFormCustomerAccountTableVerify = () => {
  formFilterCopy.accountTypeFilter = formFilter.accountTypeFilter;
  formFilterCopy.accountNoFilter = formFilter.accountNoFilter;
  formFilterCopy.belongBankFilter = formFilter.belongBankFilter;
  formFilterCopy.openAccountBackFilter = formFilter.openAccountBackFilter;
  formFilterCopy.openAccountNameFilter = formFilter.openAccountNameFilter;
  formFilterCopy.openAccountPhoneFilter = formFilter.openAccountPhoneFilter;
  return true;
};
/**
 * 新建
 */
const onAddCustomerAccountClick = (row?: CustomerAccountData) => {
  let params: ANY_OBJECT = {
  };

  Dialog
    .show('新建', FormEditCustomerAccount, { area: '900px' }, { ...params, subPage: true })
    .then(res => {
      formCustomerAccountTableWidget.refreshTable();
    }).catch(e => {
      // TODO: 异常处理
      console.error(e);
    });
};
/**
 * 编辑
 */
const onEditCustomerAccountClick = (row?: CustomerAccountData) => {
  let params: ANY_OBJECT = {
    accountId: row?.accountId,
  };

  Dialog
    .show('编辑', FormEditCustomerAccount, { area: '900px' }, { ...params, subPage: true })
    .then(res => {
      formCustomerAccountTableWidget.refreshTable();
    }).catch(e => {
      // TODO: 异常处理
      console.error(e);
    });
};
/**
 * 导出
 */
const onExportCustomerAccountClick = (row?: CustomerAccountData) => {
  let params: ANY_OBJECT = {
  };

  CustomerAccountController.export(params, '表格组件.xlsx').then(res => {
    ElMessage.success('导出成功');
  }).catch(e => {
    ElMessage.error(e.errorMessage);
  });
};
/**
 * 导入
 */
const onImportCustomerAccountClick = (file) => {
  let params: ANY_OBJECT = {
    importFile: file.raw,
    // 是否忽略表头
    skipHeader: false
  };

  CustomerAccountController.import(params).then(res => {
    ElMessage.success('导入成功');
    formCustomerAccountTableWidget.refreshTable();
  }).catch(e => {
    // TODO: 异常处理
    console.error(e);
  });
};
/**
 * 删除
 */
const onDeleteCustomerAccountClick = (row?: CustomerAccountData) => {
  let params: ANY_OBJECT = {
    accountId: row?.accountId,
  };

  ElMessageBox.confirm('是否删除此记录？').then(res => {
    CustomerAccountController.delete(params).then(res => {
      ElMessage.success('删除成功');
      formCustomerAccountTableWidget.refreshTable(false, 1);
    }).catch(e => {
      // TODO: 异常处理
      console.error(e);
    });
  }).catch(e => {
    // TODO: 异常处理
    console.error(e);
  });
};
// 表格组件表格组件参数
const formCustomerAccountTableOptions: TableOptions<CustomerAccountData> = {
  loadTableData: loadFormCustomerAccountTableWidgetData,
  verifyTableParameter: loadFormCustomerAccountTableVerify,
  paged: true,
  rowSelection: false,
  orderFieldName: undefined,
  ascending: true,
};
// 表格组件表格组件
const formCustomerAccountTable = ref();
const formCustomerAccountTableWidget = useTable(formCustomerAccountTableOptions);
const {
  dataList: formCustomerAccountTableWidgetDataList,
  currentPage: formCustomerAccountTableWidgetCurrentPage,
  pageSize: formCustomerAccountTableWidgetPageSize,
  totalCount: formCustomerAccountTableWidgetTotalCount,
} = formCustomerAccountTableWidget;
/**
 * 账户类型下拉数据获取函数
 */
const loadAccountTypeFilterDropdownList = (): Promise<ListData<DictData>> => {
  return Promise.resolve({
    dataList: StaticDict.BankCardType.getList(),
  });
};
// 账户类型配置参数
const accountTypeFilterOptions: DropdownOptions<DictData> = {
  loadData: loadAccountTypeFilterDropdownList,
  isTree: false,
};
// 账户类型下拉组件
const accountTypeFilterWidget = useDropdown(accountTypeFilterOptions);
const { dropdownList: accountTypeFilterWidgetDropdownList } = accountTypeFilterWidget
const refreshFormCustomerAccount = () => {
  // 刷新段落
  formCustomerAccountTableWidget.refreshTable();
};
/**
 * 重置过滤值
 */
const resetFormCustomerAccount = () => {
  formFilter.accountTypeFilter = undefined;
  formFilterCopy.accountTypeFilter = undefined;
  formFilter.accountNoFilter = undefined;
  formFilterCopy.accountNoFilter = undefined;
  formFilter.belongBankFilter = undefined;
  formFilterCopy.belongBankFilter = undefined;
  formFilter.openAccountBackFilter = undefined;
  formFilterCopy.openAccountBackFilter = undefined;
  formFilter.openAccountNameFilter = undefined;
  formFilterCopy.openAccountNameFilter = undefined;
  formFilter.openAccountPhoneFilter = undefined;
  formFilterCopy.openAccountPhoneFilter = undefined;
  refreshFormCustomerAccount();
};
/**
 * 重置所有过滤值
 */
const resetFilter = () => {
  resetFormCustomerAccount();
};
const formInit = () => {
  accountTypeFilterWidget.onVisibleChange(true).catch(e => {console.error(e)});
  refreshFormCustomerAccount();
};

onMounted(() => {
  formInit();
});

onActivated(() => {
  onResume();
});
</script>